package com.cube.reactive.guide.client;

import com.cube.reactive.guide.pojo.Greeting;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author cube.li
 * @date 2021/11/14 10:25
 * @description 客户端
 * 与RestTemplate不同的是,WebClient是一个非阻塞的网络请求工具,适合在响应式编程中使用
 */
@Component
public class GreetingClient {

    private final WebClient webClient;

    /**
     * Spring Boot auto-configures a `WebClient.Builder` instance with nice defaults and customizations.
     * We can use it to create a dedicated `WebClient` for our component.
     *
     * @param builder builder
     */
    public GreetingClient(WebClient.Builder builder) {
        this.webClient = builder.baseUrl("http://localhost:8080").build();
    }

    public Mono<String> getMessage() {
        return this.webClient.get().uri("/hello").accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(Greeting.class)
                .map(Greeting::getMessage);
    }
}
